﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using CookComputing.XmlRpc;
using System.Collections.Generic;
using MyMainSite.Repositories;

namespace MyMainSite.MetaWeblog
{
    public class MetaWeblog : XmlRpcService, IMetaWeblog
    {
        #region Public Constructors

        public MetaWeblog()
        {
        }

        #endregion

        #region IMetaWeblog Members

        string IMetaWeblog.AddPost(string blogid, string username, string password,
            Post post, bool publish)
        {
            if (ValidateUser(username, password))
            {
                int blogId = BlogEntryRepository.AddFromMetaWeblogPost(post, Convert.ToInt32(blogid));

                return blogid.ToString();
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        bool IMetaWeblog.UpdatePost(string postid, string username, string password,
            Post post, bool publish)
        {
            if (ValidateUser(username, password))
            {
                bool result = BlogEntryRepository.UpdateFromMetaWeblogPost(post, Convert.ToInt32(postid));

                return result;
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        Post IMetaWeblog.GetPost(string postid, string username, string password)
        {
            if (ValidateUser(username, password))
            {
                Post post = new Post();

                var entry = BlogEntryRepository.GetById(Convert.ToInt32(postid));

                post.dateCreated = entry.DateCreated;
                post.description = entry.BodyHtml;
                post.permalink = entry.FriendlyUrl;
                post.postid = entry.BlogEntryId;
                post.title = entry.Title;
                post.userid = BlogUserRepository.GetByUserName(username).BlogUserId.ToString();

                return post;
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        CategoryInfo[] IMetaWeblog.GetCategories(string blogid, string username, string password)
        {
            if (ValidateUser(username, password))
            {
                List<CategoryInfo> categoryInfos = new List<CategoryInfo>();

                // we don't really use categories
                CategoryInfo ci = new CategoryInfo();
                ci.categoryid = 1.ToString();
                ci.description = "Main";
                ci.htmlUrl = "/";
                ci.rssUrl = "/";
                ci.title = "Main Title";

                categoryInfos.Add(ci);

                return categoryInfos.ToArray();
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        Post[] IMetaWeblog.GetRecentPosts(string blogid, string username, string password,
            int numberOfPosts)
        {
            if (ValidateUser(username, password))
            {
                List<Post> posts = new List<Post>();

                string userId = BlogUserRepository.GetByUserName(username).BlogUserId.ToString();

                var entries = BlogEntryRepository.GetRecentEntriesByBlogId(Convert.ToInt32(blogid), numberOfPosts);

                foreach (var entry in entries)
                {
                    Post post = new Post();

                    post.dateCreated = entry.DateCreated;
                    post.description = entry.BodyHtml;
                    post.permalink = entry.FriendlyUrl;
                    post.postid = entry.BlogEntryId;
                    post.title = entry.Title;
                    post.userid = userId;

                    posts.Add(post);
                }

                return posts.ToArray();
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        MediaObjectInfo IMetaWeblog.NewMediaObject(string blogid, string username, string password,
            MediaObject mediaObject)
        {
            if (ValidateUser(username, password))
            {
                MediaObjectInfo objectInfo = new MediaObjectInfo();

                MetaWeblogImageRepository.Add(mediaObject.name, mediaObject.bits, mediaObject.type);

                objectInfo.url = String.Format("/services/MetaWeblogImage.ashx?name={0}", mediaObject.name);

                return objectInfo;
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        bool IMetaWeblog.DeletePost(string key, string postid, string username, string password, bool publish)
        {
            if (ValidateUser(username, password))
            {
                bool result = BlogEntryRepository.DeleteById(Convert.ToInt32(postid));

                return result;
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        BlogInfo[] IMetaWeblog.GetUsersBlogs(string key, string username, string password)
        {
            if (ValidateUser(username, password))
            {
                List<BlogInfo> infoList = new List<BlogInfo>();

                var user = BlogUserRepository.GetByUserName(username);

                if (user != null)
                {
                    var blogs = BlogRepository.GetByBlogUserId(user.BlogUserId);

                    foreach (var blog in blogs)
                    {
                        BlogInfo info = new BlogInfo();

                        info.blogid = blog.BlogId.ToString();
                        info.blogName = blog.Name;
                        info.url = String.Format("/blog/index/{0}", blog.Name);

                        infoList.Add(info);
                    }
                }

                return infoList.ToArray();
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        UserInfo IMetaWeblog.GetUserInfo(string key, string username, string password)
        {
            if (ValidateUser(username, password))
            {
                UserInfo info = new UserInfo();

                var user = BlogUserRepository.GetByUserName(username);
                if (user != null)
                {
                    info.email = user.EMailAddress;
                    info.firstname = user.FirstName;
                    info.lastname = user.LastName;
                    info.nickname = user.UserName;
                    info.url = user.Url;
                    info.userid = user.BlogUserId.ToString();
                }

                return info;
            }
            throw new XmlRpcFaultException(0, "User is not valid!");
        }

        #endregion

        #region Private Methods

        private bool ValidateUser(string username, string password)
        {
            return BlogUserRepository.ValidateUser(username, password);
        }

        #endregion
    }
}